import { AdvanceTreeNode, AdvanceTreePlainNode } from ".";

export const rootNode = "00000000-0000-0000-0000-000000000000";

export function flatTreeData(data: AdvanceTreeNode[]): AdvanceTreePlainNode[] {
  const flatData: AdvanceTreePlainNode[] = [];

  function flatChildren(node: AdvanceTreeNode, pid: number | string) {
    flatData.push({ ...node, pid, uuid: node.key });
    if (node.children) {
      node.children.forEach((c) => flatChildren(c, node.key));
    }
  }

  data.forEach((t) => flatChildren(t, rootNode));

  return flatData;
}

export function buildTreeData(
  pid: number | string,
  data: AdvanceTreePlainNode[]
): AdvanceTreeNode[] {
  function findChildren(key: string | number): AdvanceTreeNode[] {
    const children: AdvanceTreeNode[] = data
      .filter((f) => f.parent === key)
      .map((c) => ({ ...c, children: findChildren(c.key) }));
    return children;
  }

  const treeData = data
    .filter((t) => t.pid === pid)
    .map((t) => ({ ...t, children: findChildren(t.key) }));

  return treeData;
}

export function loop(
  data: AdvanceTreeNode[],
  key: string | number,
  callback: (
    item: AdvanceTreeNode,
    index: number,
    arr: AdvanceTreeNode[]
  ) => void
) {
  for (let i = 0; i < data.length; i++) {
    if (data[i].key === key) {
      return callback(data[i], i, data);
    }
    if (data[i].children) {
      loop(data[i].children, key, callback);
    }
  }
}
